package com.tools.cleanmaster.scenenew;

import android.app.ActivityManager;
import android.content.Context;
import android.net.TrafficStats;
import android.text.TextUtils;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.store.SceneSharedPrefManager;
import com.tools.cleanmaster.taskmain.AppTaskUtils;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.ui.notification.NotificationBaseItem;
import com.tools.cleanmaster.ui.notification.item.NetflowScreenOffItem;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 锁屏流量扫描帮助类
 */
public class NetflowScreenOffHelper {
    private ArrayList<Long> mRecordBytes = new ArrayList<Long>();
    private ArrayList<ProcessItem> mRecordProcess = new ArrayList<ProcessItem>();

    private NetflowScreenOffHelper(){}
    private static NetflowScreenOffHelper mInstance = null;

    public static NetflowScreenOffHelper getInstance() {
        if(mInstance == null) {
            synchronized (NetflowScreenOffHelper.class) {
                if(mInstance == null) {
                    mInstance = new NetflowScreenOffHelper();
                }
            }
        }
        return mInstance;
    }

    /**
     * 锁屏记录流量数据
     */
    public void recordData() {
        mRecordBytes.clear();
        mRecordProcess.clear();
        HashMap<String, ProcessItem> processMap = new HashMap<String, ProcessItem>();
        Context context = CleanApplication.getInstance();
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        AppTaskUtils.getRunningTaskList(context, manager, processMap, false, false, null);
        for (ProcessItem process : processMap.values()) {
            if(process.isSelf || process.sys || process.isSuggestedProtected) {
                continue;
            }

//            if (BackCallUiManager.getInstance().isSuggestProtected(process.pkgName, true)) {   // 排除建议保留名单
//                continue;
//            }
            if(SceneToolkit.isDefaultProtected(process.pkgName)) {   // 排除默认保护
                continue;
            }
            int uid = process.uid;
            long bytesCount = TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid);
            if (FeatureConfig.DEBUG_LOG) {
                log("记录：pkgName= " + process.pkgName + " ,UID = " + uid + ", bytesCount = " + bytesCount);
            }
            mRecordBytes.add(bytesCount);
            mRecordProcess.add(process);
        }
    }

    /**
     * 开屏计算流量数据
     */
    public String calcData() {
        String resultPkg = null;
        long resultBytes = 0;
        long minFlowByte = getThreshold();
        for(int i = 0; i < mRecordProcess.size(); ++i) {
            ProcessItem processItem = mRecordProcess.get(i);
            long diffBytes = TrafficStats.getUidTxBytes(processItem.uid) + TrafficStats.getUidRxBytes(processItem.uid) -
                    mRecordBytes.get(i);
            if (FeatureConfig.DEBUG_LOG) {
                log("判断：pkgName= " + processItem.pkgName + "diffBytes = " + diffBytes + ", mMinFlowByte " + minFlowByte);
            }
            if(diffBytes >= minFlowByte && diffBytes > resultBytes) {
                resultBytes = diffBytes;
                resultPkg = processItem.pkgName;
            }
        }
        if(!TextUtils.isEmpty(resultPkg)) {
            if (FeatureConfig.DEBUG_LOG) {
                log("锁屏流量消耗满足条件");
            }
        } else {
            if (FeatureConfig.DEBUG_LOG) {
                log("锁屏流量消耗不满足条件，无法展示");
            }
        }
        return resultPkg;
    }

    private void log(String message) {
        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.d(NotificationBaseItem.TAG, message);
        }
    }

    private long getThreshold() {
        String jsonBody = SceneSharedPrefManager.getSingleSceneConfigData(SceneType.NETFRQ_SCREENOFF);
        long mMinFlowKB = NetflowScreenOffItem.DEFAULT_FLOW_KB;
        try {
            JSONObject jsonObject = new JSONObject(jsonBody);
            mMinFlowKB = jsonObject.optInt(NetflowScreenOffItem.JSON_KEY_FLOW, NetflowScreenOffItem.DEFAULT_FLOW_KB);
        } catch (JSONException e) {
            if (FeatureConfig.DEBUG_LOG) {
                e.printStackTrace();
            }
        }
        return mMinFlowKB * 1024;
    }
}
